﻿using System;
using System.Collections.Generic;
using UnityEngine;

public class DouglasPeuckerReduction
{
    public static float PerpendicularDistance(Vector2 Point1, Vector2 Point2, Vector2 Point)
    {
        float num = Mathf.Abs((float) (0.5f * ((((((Point1.x * Point2.y) + (Point2.x * Point.y)) + (Point.x * Point1.y)) - (Point2.x * Point1.y)) - (Point.x * Point2.y)) - (Point1.x * Point.y))));
        float num2 = Mathf.Sqrt(Mathf.Pow(Point1.x - Point2.x, 2f) + Mathf.Pow(Point1.y - Point2.y, 2f));
        return ((num / num2) * 2f);
    }

    public static List<Vector2> Reduce(List<Vector2> Points, float Tolerance)
    {
        Vector2 vector;
        if ((Points == null) || (Points.Count < 3))
        {
            return Points;
        }
        int firstPoint = 0;
        int lastPoint = Points.Count - 1;
        List<int> pointIndexsToKeep = new List<int> {
            firstPoint,
            lastPoint
        };
    Label_003C:
        vector = Points[firstPoint];
        if (vector.Equals(Points[lastPoint]))
        {
            lastPoint--;
            goto Label_003C;
        }
        Reduce(Points, firstPoint, lastPoint, Tolerance, ref pointIndexsToKeep);
        List<Vector2> list2 = new List<Vector2>();
        pointIndexsToKeep.Sort();
        foreach (int num3 in pointIndexsToKeep)
        {
            list2.Add(Points[num3]);
        }
        return list2;
    }

    private static void Reduce(List<Vector2> points, int firstPoint, int lastPoint, float tolerance, ref List<int> pointIndexsToKeep)
    {
        float num = 0f;
        int item = 0;
        for (int i = firstPoint; i < lastPoint; i++)
        {
            float num4 = PerpendicularDistance(points[firstPoint], points[lastPoint], points[i]);
            if (num4 > num)
            {
                num = num4;
                item = i;
            }
        }
        if ((num > tolerance) && (item != 0))
        {
            pointIndexsToKeep.Add(item);
            Reduce(points, firstPoint, item, tolerance, ref pointIndexsToKeep);
            Reduce(points, item, lastPoint, tolerance, ref pointIndexsToKeep);
        }
    }
}

